<?php
require_once("lib/api.php");
require_once("res/const.php");
$api = new api();
$thumb = false;

if (isset($_GET['thumb'])) {
	$thumb = true;
	
}

if (isset($_GET['amount'])) {
    $amount = $_GET['amount'];
    if (!is_numeric($amount)) {
        $api->setYouFail("Needs to be a number.");
    } elseif (!($amount > 0)) {
        $api->setYouFail("Needs to be a number larger than 0.");
    } elseif(!($amount < $MAX_NUMBER_POSTS ))  {
        $api->setYouFail("Needs to be a number smaller than $MAX_NUMBER_POSTS.");
    } else {
        require_once("lib/post/view.php");
        if ($res = getLatest($amount)) {//, JSON_FORCE_OBJECT
            foreach ($res as &$post) {
            	if ($post['img'] != NULL) {
            		$postid = $post['postid'];
            		$imgInfo = getimagesize("../../res/image/image_$postid.gif");
            		if ($thumb && ($imgInfo[0] > $IMGTHUMB_WIDTH || $imgInfo[1] > $IMGTHUMB_HEIGHT)) {
            			$post['img'] = $THUMBNAIL_PATH . "image_" . $postid . "-thumb.gif";
            		} else {
            			$post['img'] = $IMAGE_PATH . "image_" . $postid . ".gif";
            		}
            	}
            }
        	$api->setOk();
            $api->setReturn("posts", $res);
        } else {
            $api->setFail("No posts found.");
        }
    }
} elseif (isset($_GET['postid'])) {
    $postid = $_GET['postid'];
    if (!is_numeric($postid)) {
        $api->setYouFail("Needs to be a number.");
    } elseif (!($postid > 0)) {
        $api->setYouFail("Needs to be a number larger than 0.");
    } else {
        require_once("lib/post/view.php");
        if ($res = getPost($_GET['postid'])) {
        	if ($res['img'] != NULL) {
        		if ($thumb) {
        			$res['img'] = $THUMBNAIL_PATH . "image_" . $postid . "-thumb.gif";
        		} else {
        			$res['img'] = $IMAGE_PATH . "image_" . $postid . ".gif";
        		}
        	}
            $api->setOk();
            $api->setReturn("posts", $res);
        } else {
            $api->setFail("No post found.");
        }
    }
}
$api->returnResponse();
?>
